var canteenLabelList = []; // 食堂等级
var categoryList; // 分类

layui.config({
    base: 'plugins/layui/modules/'
}).use(['form', 'http'], function () {
    var  form = layui.form,
        http = layui.http;

    var id = http.getPid('id');
    if(id){
        $('.block_title').html('修改商品信息')
            document.title = '修改商品'
        $('.sure').html('修改申请')
    }else{
        $('.block_title').html('新增商品信息')
            document.title = '新增商品'
        $('.sure').html('上架申请')
    }

    // 单位列表查询
    getUnit()
    function getUnit() {
        http.get('supplier/admin/product/unit/listAll',{}, function(res){
            if(res.code == 200){
                var html = '<option value=""></option>';
                var list = res.data;
                for (var i = 0; i < list.length; i++) {
                    html += '<option value="' + list[i].id + '">' + list[i].name + '</option>'
                }
                $('select[name=unit]').html(html);
                form.render('select');
            }else{
                layer.msg(res.msg)
            }
        })
    }

            
    // -------------- 品牌 start --------------------
    http.get('supplier/admin/product/brand/listAll',{},function(res){
        if(res.code == 200){
            var html = '<option value=""></option>';
            var data = res.data;
            for (var i = 0; i < data.length; i++) {
                html += '<option value="' + data[i].id + '">' + data[i].name + '</option>'
            }
            $('select[name=brand]').html(html);
            form.render('select');
        }else{
            layer.msg(res.msg)
        }
    })
    // -------------- 品牌 end --------------------

    // -------------- 分类 start --------------------	
    http.get('supplier/admin/product/category/listAll',{},function(res){
        if(res.code == 200){
            var html = '<option value="">一级分类</option>';
            categoryList = res.data;
            for (var i = 0; i < categoryList.length; i++) {
                html += '<option value="' + categoryList[i].id + '">' + categoryList[i].categoryName + '</option>'
            }
            $('select[name=parentId]').html(html);
			
            if(id) // 修改商品的时候
                getInfo();// 商品详情
                
            form.render('select');
        }
    })
    
    //监听一级分类
    form.on('select(parentId)', function(data){
        if(data.value){
            selectCategoryMore(data.value)
        }else{
            $('select[name=categoryId]').html(
                '<option value="">二级分类</option>'
            );
        }
        form.render();
    });
    
    // 查询下级
    function selectCategoryMore(parentId,categoryId){
        for(var i=0;i<categoryList.length;i++){
            if(categoryList[i].id == parentId){
                var html = '<option value="">二级分类</option>';
                var data = categoryList[i].childCategory;
                if(data){
                    for (var i = 0; i < data.length; i++) {
                        html += '<option value="' + data[i].id + '">' + data[i].categoryName + '</option>'
                    }
                }
                $('select[name=categoryId]').html(html);
                if(categoryId && categoryId != parentId){
                    $('select[name=categoryId]').val(categoryId);
                }
                form.render('select');
                break
            }

        }
    }

    function categoryFunction(categoryId){
        http.get('supplier/admin/product/category/listAllByCategoryId',{
            categoryId: categoryId
        },function(res){
            if(res.code == 200){
                $('select[name=parentId]').val(res.data.id);
                selectCategoryMore(res.data.id,categoryId)
            }else{
                layer.msg(res.msg)
            }
        })
    }
    // -------------- 分类 end --------------------



    // 列表查询所有食堂等级
    http.get('supplier/admin/label/listAll',{
        page: 1,
        limit: 10
    },function(res){
        if(res.code == 200){
            canteenLabelList = res.data
            var html = ''
            for(var g=0;g<canteenLabelList.length;g++){
                html += '<div class="layui-form-item"><label class="layui-form-label namelabel"><span class="redtext marginRight">*</span>'+canteenLabelList[g].labelName+'单价：</label><div class="layui-input-inline"><input type="text" class="layui-input" name="label'+canteenLabelList[g].id+'" placeholder="请输入'+canteenLabelList[g].labelName+'单价" maxlength="20"/></div></div>'
            }
            $('.other_price').html(html)
        }else{
            layer.msg(res.msg)
        }
    })

				
    // 商品详情
    var load
    function getInfo(){
        http.get('supplier/admin/product/findById',{productId:id},function(res){
            var data = res.data;
            productDetail = JSON.stringify(data)
            productDetail = JSON.parse(productDetail)	
            
            load = layer.load(1, {
                shade : 0.3
            });
            $('input[name=name]').val(data.name);
            $('select[name=brand]').val(data.brand)
            $('select[name=unit]').val(data.unit)
            $('input[name=sortNumber]').val(data.sortNumber)
            $('input[name=searchKeyWord]').val(data.searchKeyWord)
            // if(data.updateStatus == 0)
            // 	$('input[name=updateStatus]').eq(1).attr('checked',true)
            // if(data.updateStatus == 1)
            // 	$('input[name=updateStatus]').eq(0).attr('checked',true)
                
            if(data.publicStatus == 0)
                $('input[name=publicStatus]').eq(1).attr('checked',true)
            if(data.publicStatus == 1)
                $('input[name=publicStatus]').eq(0).attr('checked',true)
                
            if(data.quoteStatus == 0)
                $('input[name=quoteStatus]').eq(1).attr('checked',true)
            if(data.quoteStatus == 1)
                $('input[name=quoteStatus]').eq(0).attr('checked',true)
                
            $('input[name=reportDueTime]').val(data.reportDueTime?data.reportDueTime.split(' ')[0]:'');
            
            // 审核不通过字段
            if(data.reviewStatus==2&&data.reviewFailureField){
                var list = data.reviewFailureField.split(',')
                for(var i=0;i<list.length;i++){
                    if(list[i])
                        $('.'+list[i]+'label').addClass('orange')
                }
            }
            if((data.reviewStatus==1||data.reviewStatus==2)&&data.reviewResult){
                $('.other_remarks').append('<div class="layui-form-item"><label class="layui-form-label">审核备注：</label><div class="layui-form-mid layui-word-aux reviewResult">'+data.reviewResult+'</div></div>')
            }
            if(data.shelfStatus!=1&&data.shelfDownReason){
                $('.other_remarks').append('<div class="layui-form-item"><label class="layui-form-label">下架备注：</label><div class="layui-form-mid layui-word-aux shelfDownReason">'+data.shelfDownReason+'</div></div>')
            }
            
            // 分类
            categoryFunction(data.categoryId)
            // 商品主图
            if(data.mainImage){
                $('.mainImg').hide()
                $('.showMImg').show().siblings('li').hide();
                var imgId = http.getUUID();
                var html = '<div id="div'+imgId+'" class="imgdiv" onmouseover="showOperation(\'span'+imgId+'\')" onmouseout="hideOperation(\'span'+imgId+'\')">'+
                                    '<img onurl="'+data.mainImage+'" src="'+(TUrl+data.mainImage)+'" id="proimg'+imgId+'">'+
                                    '<ul class="imgul" id="span'+imgId+'">'+
                                        '<li onclick="deleteimg(\'div'+imgId+'\')">移除</li>'+
                                    '</ul>'+
                                '</div>';
                
                $('.showMImg').html(html);
            }
            //商品图片
            if(data.smallPic){
                $('.detailsImg').hide()
                $('.showDImg1').show().siblings('li').hide();
                var imghtml = '';
                var smallPic = JSON.parse(data.smallPic);
                for(var i=0;i<smallPic.length;i++){
                    var imgId = http.getUUID();
                    imghtml += '<div id="div'+imgId+'" class="imgdiv" onmouseover="showOperation(\'span'+imgId+'\')" onmouseout="hideOperation(\'span'+imgId+'\')">'+
                                    '<img onurl="'+smallPic[i]+'" src="'+(TUrl+smallPic[i])+'" id="proimg'+imgId+'">'+
                                    '<ul class="imgul" id="span'+imgId+'">'+
                                        '<li onclick="deleteimg(\'div'+imgId+'\')">移除</li>'+
                                    '</ul>'+
                                '</div>';
                }
                $('.showDImg1').html(imghtml);
            }
                    
            document.getElementById("demo2").innerHTML = unescape(data.content);
            editor1.txt.html($('#demo2').html());//商品详情

            // 附件
            var annexFiles = JSON.parse(data.annexFiles);
            if(annexFiles && annexFiles.length>0){ 
                for(var i=0;i<annexFiles.length;i++){
                    var html = '<li><span data-url="'+annexFiles[i].file+'" class="fileUpLoadName">'+annexFiles[i].filename+'</span><span class="fileUpLoadView">删除</span></li>';
                    $('.fileList').append(html);
                }
            }
            // if(data.annexFiles){
            // 	$('.fileUpLoadDiv').show()
            // 	var annexFiles1 = JSON.parse(data.annexFiles)
            // 	annexFiles = annexFiles1
            // 	var html = ''
            // 	for(var j=0;j<annexFiles1.length;j++){
//                        html += '<div><span class="fileUpLoadName" data-file="'+annexFiles1[j].file+'">'+annexFiles1[j].filename+'</span><span class="fileUpLoadView" data-index="'+j+'">删除</span></div>'
            // 	}
            // 	$('.fileUpLoadDiv').append(html)
            // }
                    
            form.render();
            
            for(var g=0;g<res.data.goodVoList.length;g++){
                goodsPrice.push({
                    price: Number(res.data.goodVoList[g].price),
                })
                var list = labelInfoWith(canteenLabelList, res.data.goodVoList[g].goodLabelPriceList) // 食堂等级列表对应价格(2020/12/8新增)
                for(var label=0;label<list.length;label++){
                    goodsPrice[g][list[label].id] = Number(list[label].goodPrice?list[label].goodPrice:data.goodVoList[g].price)
                }
            } 
                //规格
            specificationList = [];
            var s = data.productSpecVoList;
            if(data.goodVoList.length == 1&&data.productSpecVoList[0].specName == '单规格'){ // 单规格
                $('input[name=totalPrice]').val(data.goodVoList[0].price)

                var list = labelInfoWith(canteenLabelList, data.goodVoList[0].goodLabelPriceList) // 食堂等级列表对应价格(2020/12/8新增)
                for(var l=0;l<list.length;l++){
                    $('.other_price input[name=label'+list[l].id+']').val(list[l].goodPrice?list[l].goodPrice:data.goodVoList[0].price);
                }
                setTimeout(function() {
                    layer.close(load);
                }, 1000)
            }else{
                $('.totalPrice').hide()
                for(var j=0;j<s.length;j++){
                    var p = {
                        name: s[j].specName
                    }
                    var p_enums = [];
                    for(var k=0;k<s[j].productSpecValueList.length;k++){
                        p_enums.push(s[j].productSpecValueList[k].specValue)
                    }
                    p.p_enums = p_enums;
                    specificationList.push(p)
                }
                guige(specificationList); //回显规格
                getTable(data.goodVoList);//回显规格值
                specificationList1 = testProduct(specificationList);//调用product.js中方法

                for(var x=0;x<data.goodVoList.length;x++){
                    var pp = {
                        "goodNo": data.goodVoList[x].goodNo,
                        "price": data.goodVoList[x].price,
                        "stockCount": 99999,
                        "goodSpecParamsList":[],                    //商品的规格
                        "goodLabelPriceList": data.goodVoList[x].goodLabelPriceList // 食堂等级价格(2020/12/5新增)
                    };
                    for(var y=0;y<data.goodVoList[x].goodSpecVoList.length;y++){
                        pp.goodSpecParamsList.push(data.goodVoList[x].goodSpecVoList[y].specValue);
                    }
                    prespeciGoodList.push(pp)
                    
                }

            }
        })
    }
    
    //回显规格
    function guige(specificationList){
        var html = '';
        for(var i=0;i<specificationList.length;i++){	
            html += '<div class="specificationDiv">' +
                            '<div class="inputList addlistf">' +
                                '<div class="layui-input-inline" style="width: 85%">' +
                                    '<input type="text" name="sName" autocomplete="off" placeholder="请输入规格名称" value="'+specificationList[i].name+'" class="layui-input">' +
                                '</div>' +
                                '<div class="layui-input-inline" style="width: 10%">' +
                                    '<a class="addSpecificationVal">添加规格值</a>' +
                                '</div>' +
                                '<i class="layui-icon layui-icon-close-fill close"></i>' +
                            '</div>' +
                            '<div class="inputList inputListTab">';
                            for(var j=0;j<specificationList[i].p_enums.length;j++){
                                html += '<div class="Bigaddtab">'+
                                            '<div class="layui-input-inline addcheckbox">' +
                                            '<input type="checkbox" name="checkName" lay-skin="primary" title="" lay-filter="seletCheck" checked="">'+
                                            '</div>' +
                                            '<div class="layui-input-inline addtab">' +
                                            '<input type="text" name="sVal" autocomplete="off" placeholder="请输入规格值" value="'+specificationList[i].p_enums[j]+'" class="layui-input"><i class="layui-icon layui-icon-close-fill close"></i>' +
                                            '</div>' +
                                        '</div>';
                            }
                html += '</div></div>';
        }
        $('.myMore').html(html);
        form.render();
    }
    
    function getTable(goodVoList){//回显规格明细
        if(goodVoList.length>0){
            var tableH = '<table class="layui-table inputTable"><thead><tr><th>商品编号</th>';
                                    
            for(var i=0;i<specificationList.length;i++){
                tableH += '<th>'+specificationList[i].name+'</th>'
            }
            tableH += '<th><div><span>默认商品价格</span><input type="number" name="price" autocomplete="off" class="layui-input"/></div></th>'

            // 食堂等级
            for(var g=0;g<canteenLabelList.length;g++){
                tableH += '<th><div><span>'+canteenLabelList[g].labelName+'单价</span><input type="number" name="label'+canteenLabelList[g].id+'" autocomplete="off" class="layui-input"/></div></th>'

            }

            tableH += '</tr></thead><tbody>';
                                    
            for(var j=0;j<goodVoList.length;j++){
                tableH += '<tr><td class="my_goodNo">'+goodVoList[j].goodNo+'</td>'
                for(var k=0;k<goodVoList[j].goodSpecVoList.length;k++){
                    tableH += '<td>'+goodVoList[j].goodSpecVoList[k].specValue+'</td>';
                }
                tableH += '<td><input type="number" name="price" autocomplete="off" class="layui-input" value="'+goodVoList[j].price+'"/></td>'
                
                // 食堂等级
                var list = labelInfoWith(canteenLabelList, goodVoList[j].goodLabelPriceList) // 食堂等级列表对应价格(2020/12/8新增)
                for (var g=0;g<list.length;g++) {
                    tableH += '<td><input type="number" name="label'+list[g].id+'" autocomplete="off" class="layui-input" value="'+(list[g].goodPrice?list[g].goodPrice:goodVoList[j].price)+'"/></td>'
                }
            }     
    
            tableH += '</tbody></table>';
    
            $('.mytable').html(tableH)
            setTimeout(function() {
                layer.close(load);
                slist() // 记录原数据
            }, 1000)
        }
    }

			
			
})

//显示图片操作
function showOperation(imgId){
    $('#'+imgId+'').show();
}
//隐藏图片操作
function hideOperation(imgId){
    $('#'+imgId+'').hide();
}
//图片移除
function deleteimg(imgId){
    $('#'+imgId+'').remove();		
}
